﻿using AudioMonito;
using AudioSourceManager;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Resources.ResXFileRef;

namespace AudioMonitor
{
    public partial class Form1 : Form
    {
        List<AudioMiniWindow> audioMiniWindows = new List<AudioMiniWindow>();

        public AudioPlayer player;

        private bool Started = false;

        public Form1()
        {
            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var config = DataJsonTool.Read<ConfigInfo>(Directory.GetCurrentDirectory(), "Config.json");
            Task.Run(() =>
            {
                foreach (var convertInfo in config.ConverterInfos)
                {
                    AddConventer(convertInfo);
                    AddWindow(convertInfo);
                    Thread.Sleep(2000);
                }
                Started = true;
            });

        }

        private void AddConventer(AudioConverterInfo convertInfo)
        {
            var converter = new MulticastAudioConverter(convertInfo);
            if (!converter.StartConversion(out string msg))
            {
                this.Invoke(new Action(() =>
                {
                    MessageBox.Show(msg);
                }));
            }
        }

        private void AddWindow(AudioConverterInfo convertInfo)
        {
            this.Invoke(new Action(() =>
            {
                var audioMiniWindow = new AudioMiniWindow();
                audioMiniWindows.Add(audioMiniWindow);
                audioMiniWindow.Dock = DockStyle.Fill;
                tableLayoutPanel1.Controls.Add(audioMiniWindow);
                audioMiniWindow.OnClick += OnAudioMiniWindowClicked;
                audioMiniWindow.StartMonitoring(convertInfo);
            }));
        }

        private void OnAudioMiniWindowClicked(AudioMiniWindow obj)
        {
            foreach (var item in audioMiniWindows)
            {
                item.Mute = item != obj;
                if (item == obj)
                {
                    if (player != null)
                    {
                        player.Stop();
                    }

                    player = new AudioPlayer();
                    var playInfo = obj.PlayInfo;
                    player.Play(playInfo.URL);
                }
            }

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            foreach (var item in audioMiniWindows)
            {
                item.UpdateVolume();
            }
            //label1.Text = player != null ? player.Log : "--";
        }
    }
}
